package com.inifitness.message.context;

import java.util.List;
import java.util.Map;

import com.inifitness.common.basic.BaseEnum;
import com.inifitness.common.event.event.MessageEvent;
import com.inifitness.message.enums.MessageChannel;
import com.inifitness.message.processor.message.MessageProcessor;
import com.inifitness.message.service.EventTemplate;
import com.inifitness.message.service.EventTemplateService;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 消息处理器上下文
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024-05-29 13:20
 */
@RequiredArgsConstructor
@Log4j2
@Component
public class MessageProcessorContext {

  private final Map<String, MessageProcessor> senderMap;
  private final EventTemplateService eventTemplateService;

  @Async
  public void sendMessage(MessageEvent event) {
    // 获取事件绑定的所有模板:
    List<EventTemplate> templates = eventTemplateService.findByEventCode(event.eventCode());

    // 遍历模板,发送消息到对应的渠道
    for (EventTemplate template : templates) {
      MessageProcessor sender = senderMap.get(
          BaseEnum.getEnumByValue(MessageChannel.class, template.getChannelType()).getSender());
      if (sender != null) {
        // 1.短信 2.站内信 3.邮件 4.微信公众号 5.待办 6.提醒 7.日志 8.弹幕 9.WS
//        String template = "小斯@邦提醒您: 系统有新的租户认证提交，租户名称:${name},联系人:${contact},联系电话:${mobile}";
        sender.process(event,template);
      } else {
        throw new IllegalArgumentException("Invalid channel type: " + template.getChannelType());
      }
    }
  }

}
